package com.kpmg.datalake.autopackage.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.autopackage.dao.ExcelTemplateMapper;
import com.kpmg.datalake.autopackage.enums.TemplateEnum;
import com.kpmg.datalake.autopackage.enums.TemplateStatusEnum;
import com.kpmg.datalake.autopackage.service.ExcelTemplateService;
import com.kpmg.datalake.autopackage.utils.ExcelOperateUtil;
import com.kpmg.datalake.autopackage.vo.ExcelTemplate;
import com.kpmg.datalake.autopackage.vo.TargetTemplateVO;
import com.kpmg.datalake.common.model.ExcelRequest;
import com.kpmg.datalake.common.utils.Utils;
import com.kpmg.datalake.common.vo.ServerResponse;
import com.kpmg.datalake.db.model.Project;
import com.kpmg.datalake.db.model.SysUsr;

/**
 * Excel模板管理模块
 * 
 * @author James
 */
@Service
public class ExcelTemplateServiceImpl implements ExcelTemplateService {

  private static final Logger logger = LoggerFactory.getLogger(ExcelTemplateServiceImpl.class);

  @Resource
  private ExcelTemplateMapper excelTemplateMapper;

  /**
   * Excel模板新增
   */

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void insertClientManage(SysUsr user, ExcelTemplate newExc, String personalPath,
      Project project) {

    // 写入模板表KPMG_CLIENT_MANAGEMENT
    ExcelTemplate exc = new ExcelTemplate();
    String tplId = Utils.getRequestNo();
    exc.setTplId(tplId);
    exc.setUploadId(user.getUsrId());
    BeanUtils.copyProperties(newExc, exc);
    excelTemplateMapper.insertSelective(exc);
    logger.info("{}写入模板表", newExc.getClientId());

  }

  /**
   * Excel模板修改
   */
  @Override
  @Transactional(rollbackFor = Exception.class)
  public void editClientManage(SysUsr user, ExcelTemplate newExc, String personalPath,
      Project project) {

    ExcelTemplate exc = new ExcelTemplate();
    BeanUtils.copyProperties(newExc, exc);
    excelTemplateMapper.updateByPrimaryKeySelective(exc);
    logger.info("{}修改模板表", newExc.getTplMgtId());

  }


  @Override
  public List<ExcelRequest> getRequestList(String projectId, String searchValue, String orderColumn,
      String orderDir, int start, int size) {

    if (start != -1 && size != -1) {
      int page;
      if (start <= 0) {
        page = 1;
      } else {
        page = start / size + 1;
      }
      PageHelper.startPage(page, size);
    }
    List<ExcelTemplate> requestList = excelTemplateMapper.selectBySearch(projectId, searchValue,
        orderColumn, orderDir == null ? "" : orderDir.toUpperCase());
    PageInfo<ExcelTemplate> requestPage = new PageInfo<>(requestList);
    long total = requestPage.getTotal();
    List<ExcelRequest> auditRequests = new ArrayList<>();
    for (ExcelTemplate request : requestList) {
      ExcelRequest item = new ExcelRequest();
      item.setClientId(request.getClientId());
      item.setClientNm(request.getClientNm());
      item.setTplMgtId(request.getTplMgtId());
      item.setTplNm(request.getTplNm());
      item.setUploadTm(request.getUploadTm());
      item.setRemark(request.getRemark());
      item.setFileUrl(request.getFileUrl());
      item.setTplType(TemplateEnum.getNameByCode(request.getTplType().intValue()));
      item.setUploadId(request.getUploadId());
      item.setTotal(total);

      auditRequests.add(item);
    }
    return auditRequests;
  }

  @Override
  public ServerResponse<PageInfo<ExcelTemplate>> qryTargetTemplate(
      TargetTemplateVO targetTemplateVO) {
    // 分页操作
    PageHelper.startPage(targetTemplateVO.getPageIndex(), targetTemplateVO.getPageSize());
    List<ExcelTemplate> targetTemplateList = excelTemplateMapper
        .qryTargetTemplate(targetTemplateVO.getProjectId(), targetTemplateVO.getInputName());


    if (!CollectionUtils.isEmpty(targetTemplateList)) {
      handleExcelTemplate(targetTemplateList);
    }
    PageInfo<ExcelTemplate> requestPageList = new PageInfo<>(targetTemplateList);
    return ServerResponse.createBySuccess("获取源数据成功", requestPageList);
  }

  private void handleExcelTemplate(List<ExcelTemplate> targetTemplateList) {
    List<Map<String, String>> sheetList;
    for (ExcelTemplate excelTemplate : targetTemplateList) {
      // 获取模板类型
      String tplTypeName = "";
      if (excelTemplate.getTplType() != null) {
        tplTypeName = TemplateEnum.getNameByCode(excelTemplate.getTplType().intValue());
      }
      excelTemplate.setTplTypeName(tplTypeName);

      if (!StringUtils.isEmpty(excelTemplate.getTotalSheet())) {
        String[] sheetNameArr;
        String[] sheetDescArr = {};
        if (!StringUtils.isEmpty(excelTemplate.getTotalSheet())) {
          if (StringUtils.isEmpty(excelTemplate.getSheetDesc())) {
            sheetNameArr = excelTemplate.getTotalSheet().split(",");
            sheetList = ExcelOperateUtil.convertArrayToList(sheetNameArr, sheetDescArr);
            excelTemplate.setSheetList(JSON.toJSONString(sheetList));
          } else {
            excelTemplate.setSheetList(excelTemplate.getSheetDesc());
          }
        }
      }

      excelTemplate
          .setUploadStatusStr(TemplateStatusEnum.getNameByCode(excelTemplate.getUploadStatus()));
    }
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public List<ExcelRequest> getRequestList(final String projectId) {
    return this.getRequestList(projectId, null, null, null, -1, -1);
  }

  @Override
  public ExcelTemplate selectByPrimaryKey(String id) {
    return excelTemplateMapper.selectByPrimaryKey(id);
  }

  @Override
  public List<ExcelTemplate> selectById(String id) {
    return excelTemplateMapper.selectById(id);
  }

  @Override
  public ServerResponse<Integer> updateByTplId(ExcelTemplate newExc) {
    int code = excelTemplateMapper.updateByTplId(newExc);
    return ServerResponse.createBySuccess("目标模板修改成功", code);
  }

  @Override
  public Integer queryTaskCount() {
    return excelTemplateMapper.queryTaskCount();
  }

}
